layui.use('table',function(){
  var table = layui.table;
  var form = layui.form;
 
 
  
  //jQuery('th[data-field="rawstockId"]').hide();
  

//  //监听行单击事件
//  table.on('row(demo)', function(obj){
//    var che =obj.tr.find("input[name='layTableCheckbox']")
//      console.log(che );
//        che.prop("checked",!che.prop('checked'));
//        
//        
//        che.prop("id","id_"+obj.data.rawstockId);
//		 
//		 
//       form.render(); //单选复选下拉框渲染
//  });
  
 //监听表格复选框选择
  table.on('checkbox(demo)', function(obj){
       form.render(); //单选复选下拉框渲染
	  var data=obj.data;
	  
	 if(obj.type=="all"){
		
		 
		 $("#checkedDiv").html("")
		 var tables=table.cache.idTest;
		 if(obj.checked==true){
			 //$("#rawstockIdText").val($("#rawstockIdText").val()+"all,");
			 	if($("#purchaseText").val()==""){
			 		 $.each(tables,function(i,item){
								$("#rawstockIdText").val($("#rawstockIdText").val()+(item.rawstockId+","))
								 $("#purchaseText").val($("#purchaseText").val()+item.rawstockId+","+item.rawstockName+","+item.rawstockPrice+","+0+","+0+","+"#")
			 		});
			 		addOrDeleteTable();
			 		showDiv();
			 		addOrDeleteSum();
				}else{
//					var purchaseTexts = new Array()
//					 var purchaseTexts=$("#purchaseText").val().split("#");
//					 $("#purchaseText").val("")
					$.each(tables,function(i,item){
						var count=0;
						 var rawstockIdTexts = new Array()
						 rawstockIdTexts=$("#rawstockIdText").val().split(",");
						 for (var j = 0; j < rawstockIdTexts.length-1; j++) {
							 if(rawstockIdTexts[j]==item.rawstockId){
								 count=1;
							  } 
						}
						 
						 
						 
						 
						 
						 var purchaseTexts = new Array()
						 var purchaseTexts=$("#purchaseText").val().split("#");
						 for (var j = 0; j < purchaseTexts.length-1; j++) {
							if(purchaseTexts[j].split(",")[0]==item.rawstockId){
								 count=1;
							} 
						}
						if(count==0){
							$("#purchaseText").val($("#purchaseText").val()+item.rawstockId+","+item.rawstockName+","+item.rawstockPrice+","+0+","+0+","+"#")
							$("#rawstockIdText").val($("#rawstockIdText").val()+(item.rawstockId+","))
						}
					});
			 
					addOrDeleteTable();
					showDiv();
					addOrDeleteSum();
				}
				
 

			  
		 }else{
 
			 
			   $.each(tables,function(i,item){
				 
				   $("#checkedDiv"+item.rawstockId).remove();
				 
				   itemDeleteNOChecked(item)
					
			 })
			 addOrDeleteTable();
			 addOrDeleteSum();
		 }
		 
		 
	 }else{
		 if(obj.checked==true){
 
	            var purchaseTexts = new Array()
	       	 var purchaseTexts=$("#purchaseText").val().split("#");
	       	 $("#purchaseText").val("")
	       	 for (var i = 0; i < purchaseTexts.length-1; i++) {
	       		if(purchaseTexts[i].indexOf(data.rawstockId)!=0){
	       			$("#purchaseText").val($("#purchaseText").val()+(purchaseTexts[i]+"#"))
	       		} 
	       	}  
			 $("#rawstockIdText").val($("#rawstockIdText").val()+(data.rawstockId+","));
			 $("#purchaseText").val($("#purchaseText").val()+data.rawstockId+","+data.rawstockName+","+data.rawstockPrice+","+0+","+0+","+"#")
			 
			  $("#checkedDiv").append("<div id='checkedDiv"+data.rawstockId+"' class='checkedDiv flag note note--success new-item' onclick='removeChecked(\"checkedDiv"+data.rawstockId+"\",\""+data.rawstockId+"\")'>" +
					  					"<div class='flag__image note__icon'><i class='fa fa-check'></i></div>"+
					  					" <div class='flag__body note__text'>"+data.rawstockName+"</div>"+
			  							"</div>")
			  addOrDeleteTable();
			 addOrDeleteSum()
		 }else{
 
			 
			 var th=$('#PurchaseTa').next().find('.layui-table-header th').get(0);
	         var checkboxId=$(th).find('input[name="layTableCheckbox"]');
			 checkboxId.removeAttr("id");
			 dataDeleteNOChecked(data)
			 $("#checkedDiv"+data.rawstockId).removeClass("new-item").addClass("remove-item");
			 setTimeout(() => {
				 $("#checkedDiv"+data.rawstockId).remove();
			}, 500);
			
			 addOrDeleteTable();
			 addOrDeleteSum();
		 }
	 }
//	 obj.checked=!obj.checked;
//	 load();
         //alert($("#"+data.rawstockId).val())
  });
 
 
  
  //表单重载
  var $ = layui.$, active = {
		    reload: function(){
		      var rawstockName = $('#rawstockName');
		      var rtId = $('#rtId');
		      
		      //执行重载    查询
		      table.reload('idTest', {
		        page: {
		          curr: 1 //重新从第 1 页开始
		        }
		        ,where: {
		        	rawstockName: rawstockName.val(),
		        	rtId: rtId.val()
		        }
		      });
		    }
		  };
  
  $('#materialSreach').on('click', function(){
    var type = $(this).data('type');
    active[type] ? active[type].call(this) : '';
  });
  
 

  
  /**
  * 增加
  */
  $('#insert').on('click', function(){
	  layer.open({
		  type: 2, //设置为iframe
		  area: ['400px', '400px'],
		  content: ['addOrUpdate.html', 'no'] //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
		  
	  	  ,end: function(){ 
			 
			 //重载刷新
			 location.reload();
		  }    	
		 
	  }); 
	          
  });
});

layui.use(['form', 'table'], function(){
	  var form = layui.form
	  var table = layui.table
	  var layer = layui.layer
	  var url="../../listenSupplier/findSupplier.action";
	  var data=null;
	  $.post(url,data,function(mes){
		  $.each(mes.data,function(i,item){
				  $("#suId").append("<option value="+item.suName+">"+item.suName+"</option>")
				  load();
		  })
	  },"json")
	  
	  var url="../../listenRawstockType/findRawstockType.action";
    	var data=null
    	$.post(url,data,function(mes){
    		 $.each(mes.data,function(i,item){
    			 if(item.rtId!=item.lisRtId){ 
    				 $("#rtId").append("<option value="+item.rtId+">"+item.rtName+"</option>")
      				  load();
 				}
		  })
    	},"json");
    	
    	

    	form.on('submit(formEdit)', function(){
    		var booleans=true;
    		var sumPrice=0;
    		 if($("#purchaseText").val()==""){
    				booleans=false;
    				layer.msg("请选择材料") 
    		 }else{
 				booleans=true;
 			}
    			    		     		
    		if(booleans){
    			
    			var boolean=false;
			    var purchaseTexts = new Array()
		        var purchaseTexts=$("#purchaseText").val().split("#");
			    for (var i = 0; i < purchaseTexts.length; i++) {
			    	if(purchaseTexts[i]){
			    		var number=$("#number_"+purchaseTexts[i].split(",")[0]).val()
						if(parseInt(number)<1){
							boolean=false;
							break ;
						}else{
							boolean=true;
						}
			    	}
			    	
				}
			   
			    if(boolean){
			    	
			    	$.ajaxSetup({
	    				async: false
	    			});
			    	var url="../../listenFinance/findByCompanyId.action";
	    			var data=null;
	    			$.post(url,data,function(mes){
	    				sumPrice=mes.companyPrice;
	    			},'json')
	    			$.ajaxSetup({
	    				async: true
	    			});
			    	if(parseFloat(sumPrice)<parseFloat($("#sumPrice").val())){
			    		var alert="公司资金不足,不能采购"+" 采购金额为："+$("#sumPrice").val()+" 公司资金为："+sumPrice;
			    		layer.msg(alert)
			    	}else{
			    		layer.msg("采购成功")
			    		var purchase=$("#sumNumber").val()+","+$("#sumPrice").val()+","+$("#suId").find("option:selected").text()+","+$("#explain").val();
			    	 
		    			var purchaseDateil=$("#purchaseText").val();
		    			var purchaseId=$("#purchaseId").val()
		    			var url="../../listenPurchase/addUpdateMaterialPurchase.action";
		    			var data={"purchase":purchase,"purchaseDateil":purchaseDateil,"purchaseId":purchaseId}
		    			$.post(url,data,function(mes){
		    				if(mes>0){
		    					  window.parent.location.reload()
		    					  var index=parent.layer.getFrameIndex(window.name);
		    					  parent.layer.close(index);
		    				  }
		    			},'json')
			    	}
			    	
			    }else{
			    	layer.msg("请输入材料采购材料数量,不能小于0")
			    }
    			
    		}
    
    			
    	  })
});

function input(obj,event){
	//var che=$(obj).parent().parent().parent().find(".layui-table-col-special input[name='layTableCheckbox']")
	
	
	var keycode = String.fromCharCode(event.which); 
	var first=$(obj).val().substr(0,1);
	var noFs=/^[0-9]*$/;
	var price=$(obj).parent().prev().html();
	var xj=$(obj).parent().next().children(".layui-input");
	
	var numbers=0;
	var prices=0;
		if($(obj).val()==""){
			$(obj).val(0)
			
			$(xj).val(parseInt(0)*parseInt(price));
		}else{
			if(!noFs.test($(obj).val())){
				$(obj).val(0)
			}else{
				if(first==0){
					$(obj).val("")
					$(obj).val(keycode)
					
				}
				$(xj).val(parseInt($(obj).val())*parseInt(price));
			}
		}
		
		var purchaseTexts = new Array()
		 var purchaseTexts=$("#purchaseText").val().split("#");
		$("#purchaseText").val("")
		$("#orderTa").find("tr").each(function(i,item){
			var numberTd=$(item).children().get(2);
			var numberInput=$(numberTd).children(".layui-input")
			var priceTd=$(item).children().get(3);
			var priceInput=$(priceTd).children(".layui-input")
			
			if($(numberInput).val()!=undefined && $(priceInput).val()!=undefined){
				numbers+=parseInt($(numberInput).val());
				prices+=parseFloat($(priceInput).val());
				console.info($(numberInput).prop("id").split("_")[1])
				 
//				for (var i = 0; i < purchaseTexts.length; i++) {
//					
//					if(purchaseTexts[i].split(",")[0]==$(numberInput).prop("id").split("_")[1]){
//						//console.info(purchaseTexts[i])
//						$("#purchaseText").val($("#purchaseText").val()+purchaseTexts[i].split(",")[0]+","+purchaseTexts[i].split(",")[1]+","+purchaseTexts[i].split(",")[2]+","+$(numberInput).val()+","+$(priceInput).val()+"#")
//					}
//				}
			}
			
			 
		})
		var id=$(obj).prop("id").split("_")[1];
		for (var i = 0; i < purchaseTexts.length; i++) {
				if(purchaseTexts[i].split(",")[0]==id){
					var tr=$(obj).parents("tr");
					var nameTd=$(tr).children().get(0);
					var priceTd=$(tr).children().get(1);
					purchaseTexts[i]=id+","+$(nameTd).html()+","+$(priceTd).html()+","+$("#number_"+id).val()+","+$("#price_"+id).val(); 
					
				}
				if(purchaseTexts[i]){
					$("#purchaseText").val($("#purchaseText").val()+purchaseTexts[i]+"#")
				}
				
			}
		 
		 
		$("#sumNumber").val(numbers)
		$("#sumPrice").val(prices)
		
	     $("#sumNumberText").val(numbers)
		$("#sumPriceText").val(prices)
}


 
function removeChecked(id,raId){
	$("#"+id).removeClass("new-item").addClass("remove-item");
	setTimeout(() => {
		$("#"+id).remove();
	}, 500);
	idDeleteNOChecked(raId)
	
	$('#PurchaseTa').next().find('.layui-table-body tr').each(function(index,item){
		var ids=$(item).find('td[data-field="rawstockId"]').text();
		if(raId==ids){
			var index=$(item).data('index');
            var che = $('#PurchaseTa').next().find('.layui-table-body tr[data-index="'+index+'"] input[name="layTableCheckbox"]')
            console.info(che)
            che.prop("checked",false)
           load();
		}
	});
	addOrDeleteTable()
	 addOrDeleteSum()
//	console.info($("#id_"+raId).prop("checked"));
//	$("#id_"+raId).prop("checked",false);
//	console.info($("#id_"+raId).prop("checked"));
//	
//	load();
}

function load(){
	var form = layui.form;
	form.render();
}

function dataDeleteNOChecked(data){
	 var rawstockIdTexts = new Array()
	 rawstockIdTexts=$("#rawstockIdText").val().split(",");
	 $("#rawstockIdText").val("")
	 for (var i = 0; i < rawstockIdTexts.length-1; i++) {
		 if(rawstockIdTexts[i].indexOf(data.rawstockId)!=0){
			 $("#rawstockIdText").val($("#rawstockIdText").val()+(rawstockIdTexts[i]+","))
		  } 
	}
	 
	 
	 
	 
	 
	 var purchaseTexts = new Array()
	 var purchaseTexts=$("#purchaseText").val().split("#");
	 $("#purchaseText").val("")
	 for (var i = 0; i < purchaseTexts.length-1; i++) {
		if(purchaseTexts[i].indexOf(data.rawstockId)!=0){
			$("#purchaseText").val($("#purchaseText").val()+(purchaseTexts[i]+"#"))
		} 
	}
}


function idDeleteNOChecked(id){
	 var rawstockIdTexts = new Array()
	 rawstockIdTexts=$("#rawstockIdText").val().split(",");
	 $("#rawstockIdText").val("")
	 for (var i = 0; i < rawstockIdTexts.length-1; i++) {
		 if(rawstockIdTexts[i].indexOf(id)!=0){
			 $("#rawstockIdText").val($("#rawstockIdText").val()+(rawstockIdTexts[i]+","))
		  } 
	}
	 
	 
	 
	 
	 
	 var purchaseTexts = new Array()
	 var purchaseTexts=$("#purchaseText").val().split("#");
	 $("#purchaseText").val("")
	 for (var i = 0; i < purchaseTexts.length-1; i++) {
		if(purchaseTexts[i].indexOf(id)!=0){
			$("#purchaseText").val($("#purchaseText").val()+(purchaseTexts[i]+"#"))
		} 
	}
}

function itemDeleteNOChecked(item){
	 var rawstockIdTexts = new Array()
	 rawstockIdTexts=$("#rawstockIdText").val().split(",");
	 $("#rawstockIdText").val("")
	 for (var i = 0; i < rawstockIdTexts.length-1; i++) {
		 if(rawstockIdTexts[i].indexOf(item.rawstockId)!=0){
			 $("#rawstockIdText").val($("#rawstockIdText").val()+(rawstockIdTexts[i]+","))
		  } 
	}
	 
	 
	 
	 
	 
	 var purchaseTexts = new Array()
	 var purchaseTexts=$("#purchaseText").val().split("#");
	 $("#purchaseText").val("")
	 for (var i = 0; i < purchaseTexts.length-1; i++) {
		if(purchaseTexts[i].indexOf(item.rawstockId)!=0){
			$("#purchaseText").val($("#purchaseText").val()+(purchaseTexts[i]+"#"))
		} 
	}
}

function addOrDeleteSum(){
	var sumNumber=0;
	var sumPrice=0;
	var purchaseTexts = new Array()
	 var purchaseTexts=$("#purchaseText").val().split("#");
	 for (var i = 0; i < purchaseTexts.length-1; i++) {
			 sumNumber+=parseInt(purchaseTexts[i].split(",")[3]);
			 sumPrice+=parseFloat(purchaseTexts[i].split(",")[4]);
		 
	}
	$("#sumNumber").val(sumNumber)
	$("#sumPrice").val(sumPrice)
	$("#sumNumberText").val(sumNumber)
	$("#sumPriceText").val(sumPrice)
}


function showDiv(){
	 var purchaseTexts = new Array()
	 var purchaseTexts=$("#purchaseText").val().split("#");
	 
	 for (var i = 0; i < purchaseTexts.length-1; i++) {
		$("#checkedDiv").append("<div id='checkedDiv"+purchaseTexts[i].split(",")[0]+"' class='flag note note--success new-item' onclick='removeChecked(\"checkedDiv"+purchaseTexts[i].split(",")[0]+"\",\""+purchaseTexts[i].split(",")[0]+"\")'>"+
								"<div class='flag__image note__icon'><i class='fa fa-check'></i></div>"+
								" <div class='flag__body note__text'>"+purchaseTexts[i].split(",")[1]+"</div>"+
									"</div>")
	}
	 
	
}

function addOrDeleteTable(){
	$("#orderTb").html("")
	 var purchaseTexts = new Array()
	 var purchaseTexts=$("#purchaseText").val().split("#");
	 for (var i = 0; i < purchaseTexts.length-1; i++) {
		 $("#orderTb").append("<tr>"+
					"<td>"+purchaseTexts[i].split(",")[1]+"</td>" +
					"<td>"+purchaseTexts[i].split(",")[2]+"</td>" +
					"<td><input type='text' name='title' id='number_"+purchaseTexts[i].split(",")[0]+"' required lay-verify='required' value='"+purchaseTexts[i].split(",")[3]+"' autocomplete='off' class='layui-input number' style='border:0px;' onkeyup='input(this,event)'></td>" +
					"<td>  <input type='text' name='title' id='price_"+purchaseTexts[i].split(",")[0]+"'  value='"+purchaseTexts[i].split(",")[4]+"' autocomplete='off' class='layui-input price' style='border:0px;' disabled='disabled'></td>" +
					"</tr>")
				load();
	}
	
}

 